var compose = require('koa-compose');
var accountService = require('../modules/account/service');
var commonService = require('../modules/common/service');
var config = require('./index');

/**
 * 设置全局登录拦截器
 */
global.loginRequired = function * (next) {
  if (this.session.member) {
    yield next;
  }
  // AJAX未登录
  else if (this.request.isAjax) {
    this.body = this.template.render(403, '请先登录');
  }
  // 其他
  else {
    if (this.request.method === 'GET') {
      this.redirect('/account/login?next=' + encodeURIComponent(this.request.url));
    }
    else {
      this.redirect('/account/login?next=' + encodeURIComponent(this.headers.referer || '/home'));
    }
  }
};

/**
 * 禁用缓存拦截器
 */
global.cacheDisabled = function * (next) {
  this.set('Cache-Control', 'no-cache, no-store, must-revalidate');
  this.set('Pragma', 'no-cache');
  this.set('Expires', 0);
  yield next;
};

// Base64解码 + 反转JSON
function decode(string) {
  var body = new Buffer(string, 'base64').toString('utf8');
  return JSON.parse(body);
}

// Base64编码 + 序列JSON
function encode(data) {
  var string = JSON.stringify(data);
  return new Buffer(string).toString('base64');
}

// 恢复数据
function * restoreSession(next) {
  var self = this;
  var data = this.cookies.get('N', {
    signed: true
  });

  if (data) {
    data = decode(data);

    // 恢复 member
    if (!this.session.member && data.mid && data.aid) {
      yield accountService.getMember(this, data.mid, data.aid).then(function (data) {
        self.session.member = data.memberEntity;
        self.session.account = data.accountEntity;
        self.session.projects = data.projectList;
        self.session.partners = data.partnerUserInfoList;
        self.session.token = data.userToken;
      }, function () {
        self.session = null;
      });
    }
  }

  yield next;
}

// 存储数据
function * storeCookie(next) {
  // 中转
  yield next;

  var copy = {};
  var data = null;

  // 覆盖SESSION
  if (this.session) {
    if (this.session.member) {
      copy.mid = this.session.member.memberId;
      copy.aid = this.session.account.accountId;
    }

    data = this.cookies.get('N', {
      signed: true
    });
    if (data) {
      data = decode(data);
    }
    if (JSON.stringify(copy) !== JSON.stringify(data)) {
      this.cookies.set('N', encode(copy), {
        overwrite: true,
        httpOnly: true,
        signed: true,
        maxAge: 365 * 24 * 60 * 60 * 1000,
      });
    }
  }
  // 登出
  else {
    data = this.cookies.get('N', {
      signed: true
    });

    if (data) {
      data = decode(data);
      // 仅保留社区信息
      copy = {
        pid: data.pid
      };
      // 保留pid信息
      this.cookies.set('N', encode(copy), {
        overwrite: true,
        httpOnly: true,
        signed: true,
        maxAge: 365 * 24 * 60 * 60 * 1000,
      });
    }
  }
}

// 基于Cookie来恢复session数据
exports.recover = compose([restoreSession, storeCookie]);